import { Component, OnInit, Input } from '@angular/core';
import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { UserService } from 'src/app/core/service/user.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-edit-user',
  templateUrl: './edit-user.component.html',
  styleUrls: ['./edit-user.component.scss']
})
export class EditUserComponent implements OnInit {
  @Input() email: string;
  @Input() firstName: string;
  @Input() lastName: string;
  @Input() userUuid: string;

  editUsersForm: FormGroup;
  info: any;

  constructor(
    private modal: NzModalRef,
    private message: NzMessageService,
    private userService: UserService,
    fb: FormBuilder
  ) {
    this.editUsersForm = fb.group({
      email: [null, Validators.compose([Validators.required, Validators.email])],
      lastName: [null, Validators.compose([Validators.required])],
      firstName: [null, Validators.compose([Validators.required])],
    });
  }

  ngOnInit() {
    this.editUsersForm.patchValue({
      email: this.email,
      lastName: this.firstName,
      firstName: this.lastName,
    });
  }

  /**
   * 编辑用户
   */
  updateCommonUser() {
    console.log('提交', this.editUsersForm.controls);
    // tslint:disable-next-line:forin
    for (const c in this.editUsersForm.controls) {
      this.editUsersForm.controls[c].markAsTouched();
    }

    if (this.editUsersForm.valid) {
      this.info = {
        'email': this.editUsersForm.controls.email.value,
        'firstName': this.editUsersForm.controls.firstName.value,
        'lastName': this.editUsersForm.controls.lastName.value,
        'userUuid': this.userUuid
      };
      this.editService(this.info, '修改');
    } else {
      this.message.error('表单校验失败', { nzDuration: 10000 });
    }
  }

  private editService(info: any, msg: string) {
    this.userService.updateCommonUser(this.info)
      .subscribe((updateCommonUser) => {
        console.log(updateCommonUser);
        if (updateCommonUser.status) {
          this.message.success(msg + '成功!', {
            nzDuration: 10000
          });
          this.modal.destroy();
        } else {
          this.message.error(msg + '失败!请检查后重新填写', {
            nzDuration: 10000
          });
        }
      });
  }

  destroyModal(): void {
    this.modal.destroy({ data: 'this the result data' });
  }

}
